package cn.buk.qms.web;

import cn.buk.qms.captcha.CaptchaException;
import cn.buk.qms.captcha.CaptchaService;
import cn.buk.common.util.VerifyCodeUtil;
import com.google.code.kaptcha.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;

/**
 *
 * @author yfdai
 * @date 2016/12/4
 */
@Controller
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @RequestMapping(value = {"/captcha.do", "/captcha/getCaptchaCode.do"})
    public ModelAndView getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException, CaptchaException {
        // 生成验证码的文本
        final String captchaKey = "CAPTCHA_" + VerifyCodeUtil.MD5(request.getRequestedSessionId() + "-" + Instant.now().toString());
        final String capText = captchaService.generateCaptchaKey(captchaKey);


        response.setDateHeader("Expires", 0);

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");


        //保存到cookie
        Cookie cookie = new Cookie(Constants.KAPTCHA_SESSION_KEY, captchaKey);
        cookie.setMaxAge(60 * 60); //cookie过时的时间长度， 单位秒
        cookie.setPath("/");
        response.addCookie(cookie);

        ServletOutputStream out = response.getOutputStream();

        try {
            out.write(captchaService.generateCaptchaImage(capText));
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}
